# coding=utf-8
import serial
import threading
import serial.tools.list_ports
import time

bps = 115200


# 终端颜色
def termcolor_init():
    from colorama import init
    #from termcolor import colored
    # use Colorama to make Termcolor work on Windows too
    init(autoreset=True)


# 输出串口列表
def print_com_list():
    port_list = list(serial.tools.list_ports.comports())

    if len(port_list) == 0:
        print("无可用串口！")
    else:
        for i in range(0, len(port_list)):
            print(port_list[i])
    port = input("输入串口名：")
    return port


# 发送输入的字符串
def send_string(port):
    while True:
        data = input()
        data = bytes(data + '\r\n', 'ascii')
        port.write(data)
        #time.sleep(5)


# 接受串口字符串
def recive_massage(port):
    while True:
        while port.inWaiting() > 0:
            myout = port.readline().decode('ascii')
            print(myout, end='')


# 打开串口
def open_seri(portx, bps = 115200, timeout = None):
    ret = False
    try:  # 打开串口，并得到串口对象
        ser = serial.Serial(portx, bps, timeout=timeout)
        if(ser.is_open):  # 判断是否成功打开
            ret = True
            th = threading.Thread(target=recive_massage, args=(
                ser,), name="recive")  # 创建一个子线程去等待读数据
            th.start()
        return ser, ret
    except Exception as e:
        print("error!", e)
        return serial, ret

if __name__ == '__main__':

    termcolor_init()
    com = print_com_list()
    com, ret = open_seri('COM' + com, bps, None)

    t2 = threading.Thread(target=send_string, args=(
        com,), name="send")  # 线程2：不断地去接收数据
    t2.start()  # 开启线程1
